package com.example.testi18n.controller;

import com.example.testi18n.entity.Student;
import com.example.testi18n.entity.User;
import com.example.testi18n.exception.OrderServiceException;
import com.example.testi18n.exception.UserServiceException;
import com.example.testi18n.exception.constant.OrderThrowException;
import com.example.testi18n.exception.constant.UserThrowException;
import com.example.testi18n.http.JsonResult;
import com.example.testi18n.interfaces.ThreadUtils;
import com.example.testi18n.mapper.StudentMapper;
import com.example.testi18n.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @author xiaobendan
 * @version v1.0.0
 * @className TestController
 * @package com.example.testi18n.controller
 * @description
 * @date 2022-09-26 13:23
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private UserService userService;



    @GetMapping("/01")
    public JsonResult<?> test01(HttpServletRequest request){
        String language = request.getHeader("language");
        // throw new UserServiceException(OrderThrowException.SERVER_ERROR);
        if (1 == 1){
            throw new UserServiceException(OrderThrowException.USER_NOT_LOGIN);
        }
        System.err.println(1/0);
        return null;
    }


    @GetMapping("/02")
    public JsonResult<?> test02(@RequestParam(value = "startTime", required = false, defaultValue = "") Date startTime,
                                @RequestParam(value = "endTime", required = false, defaultValue = "") Date endTime){
        throw new UserServiceException(UserThrowException.PERMISSION_LIMIT);
    }

    @GetMapping("/03")
    public void test03(){

        throw new OrderServiceException(OrderThrowException.PAGE_NOT_FOUND);
    }
    @GetMapping("/04")
    public void test04(){
        throw new UserServiceException(UserThrowException.SERVICE_EXCEPTION,"出错了");
    }

    @GetMapping("/05")
    public JsonResult<?> generatorPdfReceipt(HttpServletResponse response) {
        try {
            String url = "/Users/xiaobendan/Desktop/ticket-8e774ea5-dcbf-4c89-af66-ebfb70e7d188.pdf";
            File file = new File(url);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] byteBuf = new byte[8192];
            int length;
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(url.substring(url.lastIndexOf("/") + 1), "UTF-8"));
            response.setContentType("application/pdf");
            response.setCharacterEncoding("UTF-8");
            OutputStream outputStream = response.getOutputStream();
            // 输出文件
            while ((length = fileInputStream.read(byteBuf)) > 0) {
                outputStream.write(byteBuf, 0, length);
            }
            // 关闭流
            outputStream.flush();
            outputStream.close();
            fileInputStream.close();
        } catch (Exception ex) {
            System.err.println("error");
        }
        return JsonResult.ok();
    }

    @GetMapping("/06")
    public JsonResult<User> test06(){

        User user = new User();
        user.setName("小狗子");
        return JsonResult.ok(user);
    }

    @GetMapping("/07")
    public JsonResult<Student> test07(){
        Student student = studentMapper.selectById(1);
        return JsonResult.ok(student);
    }
    @GetMapping("/08")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<Student> test08(){
        Student student = new Student();
        student.setName("小狗子");
        studentMapper.insert(student);

        try {
            System.err.println(1/0);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return JsonResult.ok(student);
    }

    @GetMapping("/09")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<Student> test09(){
        Student student = new Student();
        student.setName("二狗子");
        studentMapper.insert(student);

        try {
            System.err.println(1/0);
        } catch (Exception e) {
            log.info("===========");
        }finally {
            throw new RuntimeException();
        }
    }


    @GetMapping("/vailDate")
    public JsonResult<?> testVailData(@RequestBody @Validated User user){

        return JsonResult.ok();
    }


    @GetMapping("/call")
    public Object testCallBack(){
        Long userId = 10001L;
        try {
            return userService.testCallBack(userId, BigDecimal.valueOf(100L), obj -> {
                System.err.println("?????????" + obj);
                Object language = sendRedPacketOnLock(obj);
                System.err.println(language);
                return language;
            });
        } catch (Exception e) {
            throw e;
        }

    }

    public Object sendRedPacketOnLock(Object obj){
//        ThreadUtils.executeInThread(callback -> {
//            System.err.println("=====我测你码=====");
//            return callback;
//        });
        System.err.println("=========" + obj);
        System.err.println("TestController.sendRedPacketOnLock执行。。。。。");
        return "TestController.sendRedPacketOnLock执行完毕-----";
    }


    @GetMapping("/ttt")
    public JsonResult<User> testUser(){
        Long userId = 1000L;
        User user = new User();
        user.setName("name");
        user.setMoney(BigDecimal.ZERO);
        user.setUserId(String.valueOf(userId));
        return JsonResult.ok(user);
    }


}
